package com.ruoyi.system.controller;

import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.system.domain.Member;
import com.ruoyi.system.domain.XmlGenerate;
import com.ruoyi.system.domain.XmlUser;
import com.ruoyi.system.service.XmlService;
import com.ruoyi.system.utils.AnalysisXml;
import com.ruoyi.system.utils.GenerateXML;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.FileSystemResource;

import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;

import java.io.File;
import java.io.IOException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Locale;
import java.util.Objects;

import static com.ruoyi.system.utils.GenerateXML.generateXML;

@RestController
@RequestMapping("/xml")
public class xmlController {

    @Resource
    XmlService xmlService;

    @Value("${xmlfile.upload-save}")
    private String uploadDir;

    @PostMapping("/getCredentials")
    public ResponseEntity<byte[]> generateXmlCredentials(@RequestBody XmlUser xmlUser ) {
        System.out.println(xmlUser);
//        Member member = xmlService.getMemberById(Long.valueOf(xmlUser.getId()));
        if( xmlUser.getShoot() != 1){
            xmlUser.setMeter10(false);
            xmlUser.setMeter25(false);
            xmlUser.setMeter25RFP(false);
            xmlUser.setMeter50(false);
            xmlUser.setShotgun(false);
        }
        XmlGenerate xmlGenerate = new XmlGenerate();
        xmlGenerate.copyFrom(xmlUser);
        if( xmlUser.getShoot() == 1){
            xmlGenerate.setArchery( 0 );
        }
//        else {
//            xmlGenerate.setArchery( 1 );
//        }
        long timeStampStar = Long.parseLong(xmlUser.getStartTime()) * 1000; // 转换为毫秒
        Date StarDate = new Date(timeStampStar);
        xmlGenerate.setStartDate(StarDate);
        long timeStampEnd = Long.parseLong(xmlUser.getEndTime()) * 1000; // 转换为毫秒
        Date EndDate = new Date(timeStampEnd);
        xmlGenerate.setEndDate(EndDate);
//        xmlGenerate.setUsername(member.getUserName());
        xmlGenerate.setUsername("随便起的名字");

        String xmlContent = generateXML(xmlGenerate);
        File file = new File(xmlContent);

        if (!file.exists()) {
            return new ResponseEntity<>(HttpStatus.NOT_FOUND);
        }

        try {
            byte[] xmlBytes = Files.readAllBytes(file.toPath());

            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_XML);

            String encodedFileName = URLEncoder.encode(file.getName(), StandardCharsets.UTF_8.toString());
            headers.setContentDispositionFormData("attachment", encodedFileName);  // 设置文件名
            headers.setContentLength(xmlBytes.length);

            return new ResponseEntity<>(xmlBytes, headers, HttpStatus.OK);

        } catch (IOException e) {
            return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR);
        }

    }
    @PostMapping(value = "/uploadCredentials", consumes = {"multipart/form-data"})
    public AjaxResult uploadCredentials(@RequestParam("file") MultipartFile file,
                                        @RequestParam("userId") Long id){
        String fileName = file.getOriginalFilename();
        long fileSize = file.getSize();
        String userId = String.valueOf(id);

        String filePath = uploadDir + fileName;
        File savedFile = new File(filePath);

        try {
            file.transferTo(savedFile);
            String filePathSaved = savedFile.getAbsolutePath();
            HashMap hashMap = AnalysisXml.authenticationXml(filePathSaved);
            if(Objects.isNull(hashMap)){
                return AjaxResult.error("空凭证异常");
            }
            String startDateString =(String) hashMap.get("Championship Start Date ");
            String endDateString =(String) hashMap.get("Championship End Date ");
            SimpleDateFormat formatter = new SimpleDateFormat("EEE MMM dd HH:mm:ss z yyyy", Locale.ENGLISH);
            Date startDate = formatter.parse(startDateString);
            Date endDate = formatter.parse(endDateString);

            System.out.println("Start Date: " + startDate);
            System.out.println("End Date: " + endDate);
            Date now = new Date();
            if (startDate.compareTo(now) > 0) {
                return AjaxResult.error("凭证无效1");
            }
            if (endDate.compareTo(now) < 0) {
                return AjaxResult.error("凭证过期");
            }
            if(startDate.compareTo(endDate) > 0){
                return AjaxResult.error("凭证无效2");
            }
            if ((hashMap.get("Access").toString().equals("true"))){
                return AjaxResult.success(hashMap);
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
        return AjaxResult.error("凭证无效3");
    }
}
